package commons.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.annotation.RequirePerms;
import com.woniuxy.commons.enums.ResultEnum;
import com.woniuxy.commons.service.AuthService;
import com.woniuxy.commons.util.JwtUtil;
import com.woniuxy.commons.util.ResponseResult;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Author: yangtao
 * @date 2021/8/6 9:31
 * @Version 1.0
 */
@Component
public class PermsInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private AuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、判断请求是否是请求handler中的方法
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //2、获取method
            Method method = handlerMethod.getMethod();
            //3、判断方法上是否有注解
            if (method.isAnnotationPresent(RequirePerms.class)){
                //4、获取注解上的值
                RequirePerms requirePerms = method.getDeclaredAnnotation(RequirePerms.class);
                String perms = requirePerms.value();
                //得到用户信息，并将用户信息权限传给auth鉴权
                //用户信息得到方式：1.从token中获取  2、将refreshtoken传给auth，然后auth重redis中获取
                //得到token
                String token = request.getHeader("authorization");
                String account = JwtUtil.getUname(token);
                //调用auth中的鉴权方法进行权限验证   参数 account，perms
                ResponseResult responseResult = authService.existPerms(account, perms);
                if (responseResult.getStatus() == ResultEnum.PERMS_YES) {
                    //有权限，放行
                    return true;
                }
                response.setContentType("application/json;charset=utf-8");
                String json = new ObjectMapper().writeValueAsString(responseResult);
                response.getWriter().write(json);
                return false;
            }
        }
        return true;
    }
}
